//
//  RootViewController.m
//  UI9_UITableView编辑
//
//  Created by dllo on 15/11/19.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import "Student.h"

@interface RootViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) NSMutableDictionary *stuDic;
@property (nonatomic, retain) UITableView *tableV;

@end

@implementation RootViewController


- (void)dealloc
{
    [_stuDic release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getData];
    
    self.tableV = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    [_tableV release];
    
#warning 编辑1 - 添加编辑键
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
   
}

#warning 编辑2 - 让tableView处于编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    // 当点击编辑的时候tableV也进入编辑状态
    [self.tableV setEditing:editing animated:animated];
}

#warning 编辑3 - 指定tabelView哪些行可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#warning 编辑4 - 指定tableView编辑的样式（添加、删除）
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section < 2) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
}

#warning 编辑5 - 编辑完成（先操作数据源，再修改UI）
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *key = [self.stuDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    
    // 删除操作
    if (UITableViewCellEditingStyleDelete == editingStyle) {
        
         // 先删数据
        [arr removeObjectAtIndex:indexPath.row];
        
        // 再改UI
        // 局部修改 - 只修改指定行
//        [self.tableV deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        
        // 全局修改 - 重新加载一遍
        [self.tableV reloadData];
        
    }
    
    if (UITableViewCellEditingStyleInsert == editingStyle) {
        
        // 先改数据
        Student *stu = [[Student alloc] init];
        stu.name = @"王宁";
        stu.sex = @"男";
        stu.age = @"23";
        stu.phone = @"13311122222";
        stu.image = @"image3.png";
        
        [arr insertObject:stu atIndex:indexPath.row];
        [stu release];
        
        
        // 再改UI
        [self.tableV insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
        
        
    }
    
   
}

#warning 移动1 - 参照编辑的添加编辑键
#warning 移动2 - 参照编辑的让tableView处于编辑状态

#warning 移动3 - 指定tableView哪些行可以移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}



#warning 移动4 - 移动完成(移动功能的逻辑)
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    
    NSString *key = [self.stuDic.allKeys objectAtIndex:sourceIndexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    
    // 根据原地址找到待操作的学生对象
    // 注意, 手动进行引用计数加1操作, 防止从数组移除后因为计数减1引起空间释放
    Student *stu = [[arr objectAtIndex:sourceIndexPath.row] retain];
    [arr removeObjectAtIndex:sourceIndexPath.row];
    
    // 找到移动的目的地
    NSString *desKey = [self.stuDic.allKeys objectAtIndex:destinationIndexPath.section];
    NSMutableArray *desArr = [self.stuDic objectForKey:desKey];
    
    [desArr insertObject:stu atIndex:destinationIndexPath.row];
    // 不要忘记release - 对应手动retain
    [stu release];
    
    // 再改UI - 注意应用局部改变时要注意原来位置是否还有数据
//    [self.tableV moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
    [self.tableV reloadData];
    
}


#warning 移动5 - 监测移动过程, 实现限制跨区移动
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{

    // 若目的区与原区不同, 则返回原地址不允许移动
    if (sourceIndexPath.section != proposedDestinationIndexPath.section) {
        return sourceIndexPath;
    } else {
        return proposedDestinationIndexPath;
    }
    
}






// 右侧
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSArray *arr = self.stuDic.allKeys;
    return arr;
}

// 区标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *temp = [self.stuDic.allKeys objectAtIndex:section];
    return temp;
}

// 区
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.stuDic.allKeys.count;
}

// 行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSString *key = [self.stuDic.allKeys objectAtIndex:section];
    NSMutableArray *stuArr = [self.stuDic objectForKey:key];
    return stuArr.count;

}
// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellStr = @"cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellStr];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellStr] autorelease];
    }
    
    NSString *key = [self.stuDic.allKeys objectAtIndex:indexPath.section];
    NSMutableArray *arr = [self.stuDic objectForKey:key];
    Student *stu = [arr objectAtIndex:indexPath.row];
    
    cell.textLabel.text = stu.name;
    cell.detailTextLabel.text = stu.phone;
    cell.imageView.image = [UIImage imageNamed:stu.image];
    return cell;
    
}

- (void)getData
{

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"HW" ofType:@"plist"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
    
    self.stuDic = [NSMutableDictionary dictionary];
    
    // 遍历学生字典
    for (NSString *key in dic) {
        NSMutableArray *arr = [NSMutableArray array];
        
        // 遍历每个key对应的数组
        for (NSDictionary *tempDic in [dic objectForKey:key]) {
            
            Student *stu = [[Student alloc] init];
//            stu.name = [tempDic objectForKey:@"name"];
//            stu.phone = [tempDic objectForKey:@"phone"];
//            stu.age = [tempDic objectForKey:@"age"];
//            stu.sex = [tempDic objectForKey:@"sex"];
//            stu.image = [tempDic objectForKey:@"image"];
            
            // 用字典给对象赋值, 字典的key值要和对象里属性的名字相同
            [stu setValuesForKeysWithDictionary:tempDic];
            
            [arr addObject:stu];
            [stu release];
            
        }
        [self.stuDic setObject:arr forKey:key];
        
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
